<template>
	<LayoutRightContainer :breadcrumb="breadcrumb">
		<div :class="$style['resource-main-container']">
			<div :class="$style['resource-filter-panel']">
				<slot name="search">
					<el-form :model="searchForm" :class="$style['search-form']" inline>
						<el-form-item v-if="scene == 'alarm'">
							<el-input v-model="searchForm.event_name" placeholder="请输入事件名称" clearable />
						</el-form-item>
						<el-form-item v-if="scene == 'alarm'">
							<el-input v-model="searchForm.device_name" placeholder="请输入设备名称" clearable />
						</el-form-item>
						<el-form-item v-if="scene == 'alarm'">
							<el-date-picker v-model="searchForm.event_time" type="datetimerange"
								:default-time="defaultTime" range-separator="~" format="YYYY-MM-DD HH:mm:ss"
								value-format="YYYY-MM-DD HH:mm:ss" start-placeholder="开始时间" end-placeholder="结束时间"
								style="margin-right: 15px;" />
						</el-form-item>
						<el-form-item
							v-if="scene == 'account' || scene == 'operation' || scene == 'config' || scene == 'userOperate'">
							<el-input v-model="searchForm.username" placeholder="请输入账户名称" clearable />
						</el-form-item>
						<el-form-item v-if="scene == 'account' || scene == 'operation' || scene == 'config'">
							<el-date-picker v-model="searchForm.time" type="datetimerange" :default-time="defaultTime"
								range-separator="~" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
								start-placeholder="开始时间" end-placeholder="结束时间" style="margin-right: 15px;" />
						</el-form-item>
						<el-form-item v-if="scene == 'fail'">
							<el-input v-model="searchForm.deviceName" placeholder="设备名称" clearable />
						</el-form-item>
						<el-form-item v-if="scene == 'userOperate'">
							<el-input v-model="searchForm.ip" placeholder="请输入登录IP" clearable />
						</el-form-item>
						<el-form-item v-if="scene == 'fail' || scene == 'userOperate'">
							<el-date-picker v-model="searchForm.time" type="datetimerange" :default-time="defaultTime"
								range-separator="~" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
								start-placeholder="开始时间" end-placeholder="结束时间" style="margin-right: 15px;" />
						</el-form-item>
						<el-form-item>
							<el-button type="primary" @click="getList">查询</el-button>
						</el-form-item>
					</el-form>
				</slot>
				<div :class="$style['resource-filter-operation']">
					<slot name="curd"></slot>
					<el-button type="primary" size="small" @click="handleExport" :icon="Download"
						:loading="loading">批量导出</el-button>
				</div>
			</div>

			<div :class="$style['resource-table-wrapper']">
				<el-table :data="tableData" ref="refTable" row-key="id" height="100%">
					<slot name="columns"></slot>
				</el-table>
			</div>

			<div :class="$style['resource-table-paging']">
				<el-pagination v-model:current-page="currentPaging.page" v-model:page-size="currentPaging.limit" small
					background layout="sizes,total,prev, pager, next" :total="currentPaging.total"
					:hide-on-single-page="false" :page-sizes="[20, 50, 100, 200]" @size-change="handleSizeChange"
					@current-change="handleCurrentChange" />
			</div>
		</div>
	</LayoutRightContainer>
</template>

<script>
import { ref, reactive } from 'vue'
import VueTypes from 'vue-types'
import { Download } from '@element-plus/icons-vue'
import { ElMessage, ElLoading } from 'element-plus'
import LayoutRightContainer from '@/views/layout-right-container.vue'
import CyIcon from '@/components/Icon.vue'
import { fetchLogsExport } from '@/api/logs.services'

export default {
	name: 'log-page-frame',
	components: {
		Download,
		CyIcon,
		LayoutRightContainer
	},
	props: {
		scene: VueTypes.string.def(''),
		pageName: VueTypes.string.def(''),
	},
	emits: [
		'get:list',
		'change:page',
		'change:size',
		'export:file'
	],
	setup(props, { emit }) {
		const refTable = ref(null)
		const scene = props.scene
		// console.log('🚀 ~ setup ~ scene:', scene)
		const defaultTime = [
			new Date(2000, 1, 1, 0, 0, 0),
			new Date(2000, 2, 1, 23, 59, 59)
		]
		const searchForm = ref({
			username: '',
			time: undefined
		})
		const currentPaging = reactive({
			page: 1,
			limit: 20,
			total: 0
		})
		const tableData = ref([])

		const breadcrumb = [
			{ label: '日志管理' },
			{ label: props.pageName }
		]

		const handleCurrentChange = (page) => {
			currentPaging.page = page

			getList()

			emit("change:page", page)
		}

		const handleSizeChange = (limit) => {
			currentPaging.limit = limit
			currentPaging.page = 1

			getList()

			emit("change:size", limit)
		}

		const getList = () => {
			const postData = {
				...searchForm.value,
				page: currentPaging.page,
				limit: currentPaging.limit
			}

			emit('get:list', postData, {
				resolve: (res) => {
					currentPaging.total = res.total
					tableData.value = res.list
				}
			})
			console.log('🚀 ~ getList ~ postData:', postData)
		}
		const loading = ref(false)
		const handleExport = async () => {
			loading.value = true
			let url = ''
			let name = ''
			switch (props.scene) {
				case 'account': //登录日志
					url = '/export/login'
					name = '系统登录日志'
					break
				case 'alarm': //报警日志
					url = '/export/event'
					name = '报警事件日志'
					break
				case 'operation': //系统操作日志
					url = '/export/operate'
					name = '系统操作日志'
					break
				case 'config'://系统配置日志
					url = '/export/setting'
					name = '系统配置日志'
					break
				case 'fail'://系统故障日志
					url = '/export/fault'
					name = '系统故障日志'
					break
				case 'userOperate'://用户操作日志
					url = '/export/userOperate'
					name = '用户操作日志'
					break
			}
			if (!url) {
				loading.value = false
				ElMessage.warning('无效操作')
				return
			}
			const loadings = ElLoading.service({
				lock: true,
				text: '正在导出...',
				background: 'rgba(0, 0, 0, 0.7)',
			})
			try {
				// 向后端请求导出文件
				const response = await fetchLogsExport(searchForm.value, url)
				// 隐藏“正在导出”提示框
				loadings.close()
				// 创建下载链接并触发下载
				const blob = response
				const link = document.createElement('a')
				const fileName = name + new Date().toLocaleString() + '.xlsx'  // 你可以动态设置文件名，或从后端获取
				link.href = URL.createObjectURL(blob)
				link.download = fileName  // 设置文件下载的名字
				link.click()  // 触发下载
			} catch (error) {
				// 处理错误
				loadings.close()
				ElMessage.error(error)
			}
			loading.value = false
		}

		getList()

		return {
			refTable,
			defaultTime,
			breadcrumb,
			searchForm,
			currentPaging,
			tableData,
			handleCurrentChange,
			handleSizeChange,
			getList,
			handleExport,
			scene,
			Download,
			loading
		}
	}
}
</script>

<style lang="scss" module>
.resource-main-container {
	box-sizing: border-box;
	display: flex;
	flex-direction: column;
	gap: 10px;
	height: 100%;
	padding: 10px;
	background: #FFF;
	border-radius: 5px;
	box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);
}

.resource-filter-panel {
	display: flex;
}

.search-form {
	display: flex;
	gap: 12px;

	& [class~="el-form-item"] {
		margin: 0;
	}

	& [class~='el-input'] {
		width: 180px;
	}
}

.resource-filter-operation {
	display: flex;
	justify-content: flex-end;
	align-items: center;
	gap: 10px;
	flex: 1 0 0;

	& [class~="el-button"]+[class~="el-button"] {
		margin: 0;
	}
}

.resource-table-filter {
	display: flex;
	align-items: center;
	padding-left: 12px;
	line-height: 1;
	font-size: 14px;
	color: #333;
}

.card-all-checkbox {
	height: 14px;
	margin-right: 12px !important;
}

.resource-table-wrapper {
	flex: 1 0 0;
	height: 0;
}

.resource-table-operation {
	display: flex;
	align-items: center;
	justify-content: center;
	gap: 10px;
	width: 100%;
	height: 100%;
}

.resource-card-wrapper {
	position: relative;
	box-sizing: border-box;
	margin: 12px 0;
	height: calc(100% - 24px);

	&:before,
	&:after {
		content: '';
		display: block;
		position: absolute;
		left: 0;
		right: 0;
		height: 1px;
		background-color: #EBEEF5;
	}

	&:before {
		top: -12px;
	}

	&:after {
		bottom: -12px;
	}
}

.resource-card-list {
	display: grid;
	grid-template-columns: repeat(auto-fit, 260px);
	gap: 20px;
	width: 100%;
	list-style: none;
}

.resource-card-item {
	position: relative;
	box-sizing: border-box;
	display: flex;
	flex-direction: column;
	width: 260px;
	height: 175px;
	background: #FFF;
	border-radius: 5px;
	border: 1px solid #EBECED;
}

.card-checkbox {
	position: absolute;
	left: 9px;
	top: 9px;
	width: 18px;
	height: 18px;
}

.card-status {
	position: absolute;
	right: 9px;
	top: 9px;
	display: flex;
	align-items: center;
	height: 24px;
	padding: 0 12px;
	border-radius: 4px;
	word-break: keep-all;
	line-height: 1;
	font-size: 14px;
	font-weight: 400;
	background-color: var(--statusBackgroundColor, rgb(144, 147, 153));
	color: var(--statusColor, '#FFF');
}

.card-info {
	flex: 1;
	display: flex;
	flex-direction: column;
	justify-content: flex-end;
}

.card-icon {
	display: block;
	width: 48px;
	height: 48px;
	line-height: 48px;
	margin: 0 auto;
	color: var(--statusColor, '#333');
}

.card-label {
	box-sizing: border-box;
	display: flex;
	justify-content: center;
	gap: 5px;
	height: 43px;
	padding-top: 10px;
	line-height: 16px;
	font-size: 16px;
	font-weight: 400;
	color: #333;
}

.card-operation {
	box-sizing: border-box;
	display: flex;
	justify-content: space-between;
	align-items: center;
	height: 37px;
	padding: 0 12px;
	border-top: 1px solid #EBECED;
}

.resource-table-paging {
	margin-left: auto;
}
</style>
